<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="学习笔记,量化投资,kaggle竞赛,深度学习,pytorch," />










<meta name="description" content="开课吧的课程笔记，0.99元买的，老师是高民权。第一天不要变成那种知道很多概念但是基本功不行的人。课程的最终收获：建立自己的深度学习框架。当你能自己创造的时候，你会彻底理解它的原理。科研分三个类型：1.描述型。2.因果推理。3.未来预测。最难的是预测。案例：波士顿房价问题。内容：1.什么是机器学习？2.KNN算法3.回归算法4.什么是损失函数，为什么它对机器学习任务很关键？5.什么是梯度下降？先加">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记99——创造你的第一个深度学习框架">
<meta property="og:url" content="https://zwdnet.github.io/2021/01/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B099%E2%80%94%E2%80%94%E5%88%9B%E9%80%A0%E4%BD%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A1%86%E6%9E%B6/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="开课吧的课程笔记，0.99元买的，老师是高民权。第一天不要变成那种知道很多概念但是基本功不行的人。课程的最终收获：建立自己的深度学习框架。当你能自己创造的时候，你会彻底理解它的原理。科研分三个类型：1.描述型。2.因果推理。3.未来预测。最难的是预测。案例：波士顿房价问题。内容：1.什么是机器学习？2.KNN算法3.回归算法4.什么是损失函数，为什么它对机器学习任务很关键？5.什么是梯度下降？先加">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/03.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/05.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/07.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/10.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/11.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/12.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/13.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/14.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2021-01-23T03:51:16.000Z">
<meta property="article:modified_time" content="2021-01-24T00:41:13.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="kaggle竞赛">
<meta property="article:tag" content="深度学习">
<meta property="article:tag" content="pytorch">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2021/01/23/量化投资学习笔记99——创造你的第一个深度学习框架/"/>





  <title>量化投资学习笔记99——创造你的第一个深度学习框架 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2021/01/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B099%E2%80%94%E2%80%94%E5%88%9B%E9%80%A0%E4%BD%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A1%86%E6%9E%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记99——创造你的第一个深度学习框架</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-23T03:51:16+00:00">
                2021-01-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  21
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>开课吧的课程笔记，0.99元买的，老师是高民权。<br>第一天<br>不要变成那种知道很多概念但是基本功不行的人。课程的最终收获：建立自己的深度学习框架。<br>当你能自己创造的时候，你会彻底理解它的原理。<br>科研分三个类型：1.描述型。2.因果推理。3.未来预测。<br>最难的是预测。<br>案例：波士顿房价问题。<br>内容：<br>1.什么是机器学习？<br>2.KNN算法<br>3.回归算法<br>4.什么是损失函数，为什么它对机器学习任务很关键？<br>5.什么是梯度下降？<br>先加载数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.datasets <span class="keyword">import</span> load_boston</span><br><span class="line">dataset = load_boston()</span><br></pre></td></tr></table></figure>
<p>探索数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(dataset[<span class="string">&quot;feature_names&quot;</span>])</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">&#x27;CRIM&#x27;</span> <span class="string">&#x27;ZN&#x27;</span> <span class="string">&#x27;INDUS&#x27;</span> <span class="string">&#x27;CHAS&#x27;</span> <span class="string">&#x27;NOX&#x27;</span> <span class="string">&#x27;RM&#x27;</span> <span class="string">&#x27;AGE&#x27;</span> <span class="string">&#x27;DIS&#x27;</span> <span class="string">&#x27;RAD&#x27;</span> <span class="string">&#x27;TAX&#x27;</span> <span class="string">&#x27;PTRATIO&#x27;</span></span><br><span class="line"><span class="string">&#x27;B&#x27;</span> <span class="string">&#x27;LSTAT&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p>看具体描述</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(dataset[<span class="string">&quot;DESCR&quot;</span>])</span><br></pre></td></tr></table></figure>
<p>具体输出太长就不列出来了。<br>看数据的值(第六列）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(dataset[<span class="string">&quot;data&quot;</span>][:,<span class="number">5</span>])</span><br></pre></td></tr></table></figure>
<p>定义问题：假设你是一个地产销售，有人要卖房子，给出估价。<br>使用pandas分析处理数据。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line">dataframe = pd.DataFrame(dataset[<span class="string">&quot;data&quot;</span>])</span><br><span class="line">dataframe.columns = dataset[<span class="string">&quot;feature_names&quot;</span>]</span><br><span class="line">dataframe[<span class="string">&quot;price&quot;</span>] = dataset[<span class="string">&quot;target&quot;</span>]</span><br><span class="line">print(dataframe.head())</span><br><span class="line"><span class="built_in">len</span>(dataframe)</span><br></pre></td></tr></table></figure>
<p>有506列数据。<br>问题：什么特征对房价影响最大？<br>用dataframe.corr()来看特征之间的相关性。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/01.png"></p>
<p>看最后一列或最后一行。<br>画热点图看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> seaborn <span class="keyword">as</span> sns</span><br><span class="line">sns.heatmap(dataframe.corr(), annot = <span class="literal">True</span>, fmt = <span class="string">&quot;.2f&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/02.png"></p>
<p>发现房屋卧室个数和房屋价格最成正相关。<br>如何依据房屋卧室的数量来估计房子面积？<br>将卧室数量与房屋价格做字典映射</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">X_rm = dataframe[<span class="string">&quot;RM&quot;</span>].values</span><br><span class="line">Y = dataframe[<span class="string">&quot;price&quot;</span>].values</span><br><span class="line">rm_to_price = &#123;r:y <span class="keyword">for</span> r, y <span class="keyword">in</span> <span class="built_in">zip</span>(X_rm, Y)&#125;</span><br></pre></td></tr></table></figure>
<p>作为一个优秀的工程师/算法工作者，代码的可读性一定是大于简洁性。<br>根据卧室数量找到最接近的房屋价格</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">find_price_by_similar</span>(<span class="params">history_price, query_x, topn = <span class="number">3</span></span>):</span></span><br><span class="line">    <span class="comment"># return np.mean([p for x, p in sorted(history_price.items(), key = lambda x_y: (x_y[0]-query_x)**2)[:topn]])</span></span><br><span class="line">    most_similar_items = <span class="built_in">sorted</span>(history_price.items(), key = <span class="keyword">lambda</span> x_y: (x_y[<span class="number">0</span>]-query_x)**<span class="number">2</span>)[:topn]</span><br><span class="line">    most_similar_prices = [price <span class="keyword">for</span> rm, price <span class="keyword">in</span> most_similar_items]</span><br><span class="line">    average_prices = np.mean(most_similar_prices)</span><br><span class="line">    <span class="keyword">return</span> average_prices</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">find_price_by_similar(rm_to_price, <span class="number">7</span>)</span><br></pre></td></tr></table></figure>
<p>rm_to_price不要写死在函数里，因为只要其值一改变函数可能就出错了。<br>职业与非职业的区别就在细节里。<br>“代码是给人看的，偶尔运行一下。”<br>上面就是KNN算法——K-Neighbor-Nearest<br>什么是机器学习？<br>学习是为了预测。通过观察已有数据预测未来数据。回归产生数值，分类产生类别。机器学习就是用计算机来学习。<br>knn算法的问题：当数据量变大时，学习时间变长。lazy learning。<br>一个更加有效的方法：找到X和Y之间的函数关系，每次要计算时输入给这个函数，就能直接获得预测值。<br>先画散点图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">plt.scatter(X_rm, Y)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/03.jpg"></p>
<p>用直线y = kx+b来拟合，如何评判拟合的“好”？<br>用Loss函数，即在拟合的时候信息损失了多少，因此叫损失函数。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/04.png"></p>
<p>上述损失函数称为误差平方均值(Mean Square Error, MSE)。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">loss</span>(<span class="params">y, yhat</span>):</span></span><br><span class="line">    <span class="keyword">return</span> np.mean((np.array(y) - np.array(yhat))**<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">real_y = [<span class="number">3</span>,<span class="number">6</span>,<span class="number">7</span>]</span><br><span class="line">y_hats = [<span class="number">3</span>,<span class="number">4</span>,<span class="number">7</span>]</span><br><span class="line">y_hats_2 = [<span class="number">3</span>,<span class="number">6</span>,<span class="number">6</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">loss(real_y, y_hats)</span><br><span class="line"><span class="number">1.3333333333333333</span></span><br><span class="line">loss(real_y, y_hats_2)</span><br><span class="line"><span class="number">0.3333333333333333</span></span><br></pre></td></tr></table></figure>
<p>因此y_hats_2要拟合得更好。<br>获得最优的k和b呢？<br>1.直接用微积分的方法计算。<br>最小二乘法。<br>当损失函数极复杂时，无法求解。<br>2.用随机模拟方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">model</span>(<span class="params">x, k, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> x*k+b</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">VAR_MAX, VAR_MIN = <span class="number">100</span>, -<span class="number">100</span></span><br><span class="line">total_times = <span class="number">1000</span></span><br><span class="line">min_loss = <span class="built_in">float</span>(<span class="string">&quot;inf&quot;</span>)</span><br><span class="line">best_k, best_b = <span class="literal">None</span>, <span class="literal">None</span></span><br><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> <span class="built_in">range</span>(total_times):</span><br><span class="line">    k, b = random.randint(VAR_MIN, VAR_MAX), random.randint(VAR_MIN, VAR_MAX)</span><br><span class="line">    loss_ = loss(Y, model(X_rm, k, b))</span><br><span class="line">    <span class="comment"># print(&quot;正在寻找....&quot;)</span></span><br><span class="line">    <span class="keyword">if</span> loss_ &lt; min_loss:</span><br><span class="line">        min_loss = loss_</span><br><span class="line">        best_k, best_b = k, b</span><br><span class="line">        print(<span class="string">&quot;在&#123;&#125;时刻我找到了更好的k:&#123;&#125;和b:&#123;&#125;，此时的loss是：&#123;&#125;&quot;</span>.<span class="built_in">format</span>(t, k, b, loss_))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">在<span class="number">0</span>时刻我找到了更好的k:-<span class="number">26</span>和b:<span class="number">22</span>，此时的loss是：<span class="number">27524.80590943083</span></span><br><span class="line">在<span class="number">2</span>时刻我找到了更好的k:<span class="number">30</span>和b:-<span class="number">13</span>，此时的loss是：<span class="number">23669.676297035574</span></span><br><span class="line">在<span class="number">7</span>时刻我找到了更好的k:-<span class="number">11</span>和b:<span class="number">3</span>，此时的loss是：<span class="number">8103.9628163774705</span></span><br><span class="line">在<span class="number">11</span>时刻我找到了更好的k:<span class="number">6</span>和b:<span class="number">54</span>，此时的loss是：<span class="number">4833.522422316206</span></span><br><span class="line">在<span class="number">12</span>时刻我找到了更好的k:<span class="number">7</span>和b:-<span class="number">30</span>，此时的loss是：<span class="number">118.71554882015812</span></span><br><span class="line">在<span class="number">69</span>时刻我找到了更好的k:<span class="number">10</span>和b:-<span class="number">35</span>，此时的loss是：<span class="number">72.23144802371542</span></span><br><span class="line">在<span class="number">198</span>时刻我找到了更好的k:<span class="number">11</span>和b:-<span class="number">44</span>，此时的loss是：<span class="number">52.125732583003945</span></span><br><span class="line">在<span class="number">615</span>时刻我找到了更好的k:<span class="number">10</span>和b:-<span class="number">39</span>，此时的loss是：<span class="number">45.72314762845849</span></span><br></pre></td></tr></table></figure>



<p>开始时更新很快，更新速度越来越慢。<br>如何更新？<br>k’ = k + -1×loss对k的偏导数/k的偏导数<br>即梯度下降。深度学习的核心，即通过梯度下降的方法，获得一组参数，使得损失函数最小。<br>程序实现</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">partial_k</span>(<span class="params">x, y, k_n, b_n</span>):</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">2</span>*np.mean((k * x + b - y) * x)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">partial_b</span>(<span class="params">x, y, k_n, b_n</span>):</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">2</span>*np.mean(k * x + b - y)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">VAR_MAX, VAR_MIN = <span class="number">100</span>, -<span class="number">100</span></span><br><span class="line">total_times = <span class="number">1000</span></span><br><span class="line">alpha = <span class="number">1e-2</span></span><br><span class="line">min_loss = <span class="built_in">float</span>(<span class="string">&quot;inf&quot;</span>)</span><br><span class="line">k_b_history = []</span><br><span class="line">best_k, best_b = <span class="literal">None</span>, <span class="literal">None</span></span><br><span class="line">k, b = random.randint(VAR_MIN, VAR_MAX), random.randint(VAR_MIN, VAR_MAX)</span><br><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> <span class="built_in">range</span>(total_times):</span><br><span class="line">    k, b = k+(-<span class="number">1</span>)*partial_k(X_rm, Y, k, b)*alpha, b+(-<span class="number">1</span>)*partial_b(X_rm, Y, k, b)*alpha</span><br><span class="line">    loss_ = loss(Y, model(X_rm, k, b))</span><br><span class="line">    <span class="comment"># print(&quot;正在寻找....&quot;)</span></span><br><span class="line">    <span class="keyword">if</span> loss_ &lt; min_loss:</span><br><span class="line">        min_loss = loss_</span><br><span class="line">        best_k, best_b = k, b</span><br><span class="line">        print(<span class="string">&quot;在&#123;&#125;时刻我找到了更好的k:&#123;&#125;和b:&#123;&#125;，此时的loss是：&#123;&#125;&quot;</span>.<span class="built_in">format</span>(t, k, b, loss_))</span><br><span class="line">        k_b_history.append([best_k, best_b])</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">在<span class="number">0</span>时刻我找到了更好的k:<span class="number">17.369569754624507</span>和b:-<span class="number">20.333675889328063</span>，此时的loss是：<span class="number">4472.292227873009</span></span><br><span class="line">在<span class="number">1</span>时刻我找到了更好的k:<span class="number">8.955317168137993</span>和b:-<span class="number">21.65957415252766</span>，此时的loss是：<span class="number">189.74333291983726</span></span><br><span class="line">在<span class="number">2</span>时刻我找到了更好的k:<span class="number">7.437325856780592</span>和b:-<span class="number">21.90134442748533</span>，此时的loss是：<span class="number">50.287029325456274</span></span><br><span class="line">在<span class="number">3</span>时刻我找到了更好的k:<span class="number">7.163792246860975</span>和b:-<span class="number">21.94747888904269</span>，此时的loss是：<span class="number">45.74489767191771</span></span><br><span class="line">在<span class="number">4</span>时刻我找到了更好的k:<span class="number">7.114825887727485</span>和b:-<span class="number">21.958309486748952</span>，此时的loss是：<span class="number">45.596062855396596</span></span><br><span class="line">在<span class="number">5</span>时刻我找到了更好的k:<span class="number">7.106383488125827</span>和b:-<span class="number">21.962768759212416</span>，此时的loss是：<span class="number">45.59029021663505</span></span><br><span class="line">在<span class="number">6</span>时刻我找到了更好的k:<span class="number">7.1052537036267704</span>和b:-<span class="number">21.966077698329645</span>，此时的loss是：<span class="number">45.589176648302995</span></span><br><span class="line">在<span class="number">7</span>时刻我找到了更好的k:<span class="number">7.105443414960139</span>和b:-<span class="number">21.969178453014266</span>，此时的loss是：<span class="number">45.58821524136252</span></span><br><span class="line">在<span class="number">8</span>时刻我找到了更好的k:<span class="number">7.105871139922058</span>和b:-<span class="number">21.97224103793258</span>，此时的loss是：<span class="number">45.58725923424064</span></span><br><span class="line">在<span class="number">9</span>时刻我找到了更好的k:<span class="number">7.1063417207669906</span>和b:-<span class="number">21.97529613305261</span>，此时的loss是：<span class="number">45.58630384763254</span></span><br><span class="line">......</span><br><span class="line">在<span class="number">990</span>时刻我找到了更好的k:<span class="number">7.525781200015785</span>和b:-<span class="number">24.643413738514344</span>，此时的loss是：<span class="number">44.839340912645646</span></span><br><span class="line">在<span class="number">991</span>时刻我找到了更好的k:<span class="number">7.526160263125433</span>和b:-<span class="number">24.64582500368794</span>，此时的loss是：<span class="number">44.83874519542314</span></span><br><span class="line">在<span class="number">992</span>时刻我找到了更好的k:<span class="number">7.526539235080919</span>和b:-<span class="number">24.64823568901914</span>，此时的loss是：<span class="number">44.83814976467313</span></span><br><span class="line">在<span class="number">993</span>时刻我找到了更好的k:<span class="number">7.52691811590416</span>和b:-<span class="number">24.65064579464738</span>，此时的loss是：<span class="number">44.837554620257855</span></span><br><span class="line">在<span class="number">994</span>时刻我找到了更好的k:<span class="number">7.527296905617073</span>和b:-<span class="number">24.653055320712067</span>，此时的loss是：<span class="number">44.836959762039605</span></span><br><span class="line">在<span class="number">995</span>时刻我找到了更好的k:<span class="number">7.527675604241565</span>和b:-<span class="number">24.655464267352567</span>，此时的loss是：<span class="number">44.83636518988075</span></span><br><span class="line">在<span class="number">996</span>时刻我找到了更好的k:<span class="number">7.5280542117995415</span>和b:-<span class="number">24.657872634708216</span>，此时的loss是：<span class="number">44.83577090364376</span></span><br><span class="line">在<span class="number">997</span>时刻我找到了更好的k:<span class="number">7.528432728312902</span>和b:-<span class="number">24.660280422918316</span>，此时的loss是：<span class="number">44.83517690319111</span></span><br><span class="line">在<span class="number">998</span>时刻我找到了更好的k:<span class="number">7.52881115380354</span>和b:-<span class="number">24.662687632122132</span>，此时的loss是：<span class="number">44.834583188385366</span></span><br><span class="line">在<span class="number">999</span>时刻我找到了更好的k:<span class="number">7.529189488293343</span>和b:-<span class="number">24.665094262458904</span>，此时的loss是：<span class="number">44.83398975908919</span></span><br></pre></td></tr></table></figure>
<p>基本上每次都在更新参数。<br>画图看看<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/05.jpg"></p>
<p>回归比knn快得多。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/06.png"></p>
<p>第二天<br>从简单线性回归到复杂神经网络<br>从手工编码求导到自动求导。<br>我们只能让计算机拟合简单的线性函数。<br>除了线性函数，还有一种常见的函数关系是S形的函数，sigmoid函数。sigmoid(x)=1/(1+e^(-x))<br>画图看看</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sigmoid</span>(<span class="params">x</span>):</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>/(<span class="number">1</span>+np.exp(-x))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sub_x = np.linspace(-<span class="number">10</span>,<span class="number">10</span>)</span><br><span class="line">plt.plot(sub_x, sigmoid(sub_x))</span><br></pre></td></tr></table></figure>

<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/07.jpg"><br>将其进行平移拉伸就可以变换成其它形式。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sigmoid</span>(<span class="params">x</span>):</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>/(<span class="number">1</span>+np.exp(-x))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">random_line</span>(<span class="params">x</span>):</span></span><br><span class="line">    k, b = random.random(), random.random()</span><br><span class="line">    <span class="keyword">return</span> k*x + b</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sub_x = np.linspace(-<span class="number">10</span>, <span class="number">10</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">plt.plot(sub_x, random_line(sigmoid(sub_x)))</span><br></pre></td></tr></table></figure>

<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/08.png"><br>画多条试试</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>):</span><br><span class="line">    plt.plot(sub_x, random_line(sigmoid(sub_x)))</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/09.png"></p>
<p>深度学习基本思想：用基本模块经过复合叠加来拟合复杂函数。这些基本模块就是所谓的激活函数(Active functions)，其作用是让模型拟合非线性关系。没激活函数就只能拟合线性函数。<br>神经网络∈机器学习∈人工智能<br>数据量很小时，神经网络的效果不好。数据量变大时，才能使用层数超过3层的神经网络（即深度网络），使用深度网络的机器学习称为深度学习。<br>偏导数的求导：链式求导法则。<br>但是如何让计算机知道？<br>定义问题：给定一个模型定义，包含参数:{k1,k2,b1,b2}，构建一个程序，让它能够求解k1,k2,b1,b2的偏导数是多少。<br>这实际上一个数据结构，图结构的问题。<br>用字典结构来存储各个节点和其后继节点。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">computing_graph = &#123;</span><br><span class="line">    <span class="string">&quot;k1&quot;</span>:[<span class="string">&quot;L1&quot;</span>],</span><br><span class="line">    <span class="string">&quot;b1&quot;</span>:[<span class="string">&quot;L1&quot;</span>],</span><br><span class="line">    <span class="string">&quot;x&quot;</span>:[<span class="string">&quot;L1&quot;</span>],</span><br><span class="line">    <span class="string">&quot;L1&quot;</span>:[<span class="string">&#x27;sigmoid&#x27;</span>],</span><br><span class="line">    <span class="string">&quot;k2&quot;</span>:[<span class="string">&quot;L2&quot;</span>],</span><br><span class="line">    <span class="string">&quot;b2&quot;</span>:[<span class="string">&quot;L2&quot;</span>],</span><br><span class="line">    <span class="string">&quot;sigmoid&quot;</span>:[<span class="string">&quot;L2&quot;</span>],</span><br><span class="line">    <span class="string">&quot;L2&quot;</span>:[<span class="string">&quot;Loss&quot;</span>],</span><br><span class="line">    <span class="string">&quot;y&quot;</span>:[<span class="string">&quot;Loss&quot;</span>]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">import</span> networkx <span class="keyword">as</span> nx</span><br><span class="line">nx.draw(nx.DiGraph(computing_graph))</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/10.jpg"></p>
<p>∂loss/∂k1 = ∂loss/∂l2 × ∂l2/∂σ × ∂σ/∂l1 × ∂l1/k1<br>用程序根据计算图获得输出。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_output</span>(<span class="params">graph, node</span>):</span></span><br><span class="line">    outputs = []</span><br><span class="line">    <span class="keyword">for</span> n, links <span class="keyword">in</span> graph.items():</span><br><span class="line">        <span class="keyword">if</span> node == n:</span><br><span class="line">            outputs += links</span><br><span class="line">    <span class="keyword">return</span> outputs</span><br><span class="line">get_output(computing_graph, <span class="string">&quot;k1&quot;</span>)</span><br><span class="line">[<span class="string">&#x27;L1&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p>如此依次在图中找到输出节点。<br>如何获得k1的偏导？<br>获得k1的输出节点<br>获得k1的输出节点的输出节点<br>直到我们找到最后一个节点。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">computing_order = []</span><br><span class="line">target = <span class="string">&quot;k1&quot;</span></span><br><span class="line">computing_order.append(target)</span><br><span class="line">out = get_output(computing_graph, target)[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> out:</span><br><span class="line">    computing_order.append(out)</span><br><span class="line">    out = get_output(computing_graph, out)</span><br><span class="line">    <span class="keyword">if</span> out:</span><br><span class="line">        out = out[<span class="number">0</span>]</span><br><span class="line">        </span><br><span class="line">computing_order</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[(<span class="string">&#x27;L1&#x27;</span>, <span class="string">&#x27;k1&#x27;</span>), (<span class="string">&#x27;sigmoid&#x27;</span>, <span class="string">&#x27;L1&#x27;</span>), (<span class="string">&#x27;L2&#x27;</span>, <span class="string">&#x27;sigmoid&#x27;</span>), (<span class="string">&#x27;Loss&#x27;</span>, <span class="string">&#x27;L2&#x27;</span>)]</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>再输出求导顺序</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">order = []</span><br><span class="line"><span class="keyword">for</span> index, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(computing_order[:-<span class="number">1</span>]):</span><br><span class="line">    order.append((computing_order[index+<span class="number">1</span>], n))</span><br><span class="line">ds = <span class="string">&quot;*&quot;</span>.join([<span class="string">&quot;∂&#123;&#125;/∂&#123;&#125;&quot;</span>.<span class="built_in">format</span>(a, b) <span class="keyword">for</span> a, b <span class="keyword">in</span> order[::-<span class="number">1</span>]])</span><br><span class="line">ds</span><br><span class="line"><span class="string">&#x27;∂Loss/∂L2*∂L2/∂sigmoid*∂sigmoid/∂L1*∂L1/∂k1&#x27;</span></span><br></pre></td></tr></table></figure>
<p>下面就可以求各个参数的导数了。<br>中间步骤可能进行超过1次，可以记录相关结果，避免重复计算。<br>如何让计算机自己根据计算图获得计算顺序？拓扑排序。<br>步骤:<br>1.选择一个没有进入的节点。如有多个，随机选一个。如k1<br>2.在图中删去上一步选择的节点，作为访问的顺序。<br>3.检查图是否为空。如不为空，跳至第一步。<br>4.若为空，将访问顺序逆序，即为求导顺序。<br>这个其实就是所谓的反向传播。</p>
<p>第三天<br>主要是实现前两节课的内容<br>一个好习惯:代码自描述。最好的文档是源代码本身。<br>先实现拓扑排序</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 拓扑排序</span></span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">toplogic</span>(<span class="params">graph</span>):</span></span><br><span class="line">    sorted_nodes = []</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> graph:</span><br><span class="line">        all_nodes_have_input = []</span><br><span class="line">        all_nodes_have_output = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> graph: </span><br><span class="line">            all_nodes_have_input += graph[n]</span><br><span class="line">            all_nodes_have_output.append(n)</span><br><span class="line">            </span><br><span class="line">        all_nodes_have_input = <span class="built_in">set</span>(all_nodes_have_input)</span><br><span class="line">        all_nodes_have_output = <span class="built_in">set</span>(all_nodes_have_output)</span><br><span class="line">        </span><br><span class="line">        need_remove = all_nodes_have_output - all_nodes_have_input</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(need_remove) &gt; <span class="number">0</span>:</span><br><span class="line">            node = random.choice(<span class="built_in">list</span>(need_remove))</span><br><span class="line">            need_to_visited = [node]</span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(graph) == <span class="number">1</span>:</span><br><span class="line">                need_to_visited += graph[node]</span><br><span class="line">            graph.pop(node)</span><br><span class="line">            sorted_nodes += need_to_visited</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">for</span> _, links <span class="keyword">in</span> graph.items():</span><br><span class="line">                <span class="keyword">if</span> node <span class="keyword">in</span> links:</span><br><span class="line">                    links.remove(node)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">raise</span> TypeError(<span class="string">&quot;图有回路，不能进行拓扑排序。&quot;</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> sorted_nodes</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">x, k, b, linear, sigmoid, y, loss = <span class="string">&quot;x&quot;</span>, <span class="string">&quot;k&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;linear&quot;</span>, <span class="string">&quot;sigmoid&quot;</span>, <span class="string">&quot;y&quot;</span>, <span class="string">&quot;loss&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">test_graph = &#123;</span><br><span class="line">    x:[linear],</span><br><span class="line">    k:[linear],</span><br><span class="line">    b:[linear],</span><br><span class="line">    linear:[sigmoid],</span><br><span class="line">    sigmoid:[loss],</span><br><span class="line">    y:[loss]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print(toplogic(test_graph))</span><br><span class="line">[<span class="string">&#x27;y&#x27;</span>, <span class="string">&#x27;x&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;linear&#x27;</span>, <span class="string">&#x27;sigmoid&#x27;</span>, <span class="string">&#x27;loss&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p>python3.9已经自带了拓扑排序。<br>下面来运用拓扑排序生成计算图。<br>先创建节点类。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, inputs = [], name = <span class="literal">None</span></span>):</span></span><br><span class="line">        self.inputs = inputs</span><br><span class="line">        self.outputs = []</span><br><span class="line">        self.name = name</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> inputs:</span><br><span class="line">            n.outputs.append(self)</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br></pre></td></tr></table></figure>
<p>再将节点转化为计算图并拓扑排序</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">convert_feed_dict_to_graph</span>(<span class="params">feed_dict</span>):</span></span><br><span class="line">    computing_graph = defaultdict(<span class="built_in">list</span>)</span><br><span class="line">    nodes = [n <span class="keyword">for</span> n <span class="keyword">in</span> feed_dict]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> nodes:</span><br><span class="line">        n = nodes.pop(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">if</span> n <span class="keyword">in</span> computing_graph:</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">        <span class="keyword">for</span> m <span class="keyword">in</span> n.outputs:</span><br><span class="line">            computing_graph[n].append(m)</span><br><span class="line">            nodes.append(m)</span><br><span class="line">            </span><br><span class="line">    <span class="keyword">return</span> computing_graph</span><br></pre></td></tr></table></figure>
<p>最后测试一下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">node_x = Node(name = <span class="string">&quot;x&quot;</span>)</span><br><span class="line">node_y = Node(name = <span class="string">&quot;y&quot;</span>)</span><br><span class="line">node_k = Node(name = <span class="string">&quot;k&quot;</span>)</span><br><span class="line">node_b = Node(name = <span class="string">&quot;b&quot;</span>)</span><br><span class="line">node_linear = Node(inputs = [node_x, node_k, node_b], name = <span class="string">&quot;linear&quot;</span>)</span><br><span class="line">node_sigmoid = Node(inputs = [node_linear], name = <span class="string">&quot;sigmoid&quot;</span>)</span><br><span class="line">node_loss = Node(inputs = [node_y, node_sigmoid], name = <span class="string">&quot;loss&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">feed_dic = &#123;</span><br><span class="line">    node_x : <span class="number">3</span>,</span><br><span class="line">    node_y : random.random(),</span><br><span class="line">    node_k : random.random(),</span><br><span class="line">    node_b : <span class="number">0.50</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sorted_nodes = toplogic(convert_feed_dict_to_graph(feed_dic))</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[x, y, k, b, linear, sigmoid, loss]</span><br></pre></td></tr></table></figure>
<p>再增加一个Placeholder类，继承Node，定于由人赋值的节点。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Placeholder</span>(<span class="params">Node</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name = <span class="literal">None</span></span>):</span></span><br><span class="line">        Node.__init__(self, name = name)</span><br><span class="line">        self.name = name</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;,人类赋值。\n&quot;</span>.<span class="built_in">format</span>(self.name))</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">convert_feed_dict_to_graph</span>(<span class="params">feed_dict</span>):</span></span><br><span class="line">    computing_graph = defaultdict(<span class="built_in">list</span>)</span><br><span class="line">    nodes = [n <span class="keyword">for</span> n <span class="keyword">in</span> feed_dict]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> nodes:</span><br><span class="line">        n = nodes.pop(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">if</span> n <span class="keyword">in</span> computing_graph:</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">isinstance</span>(n, Placeholder):</span><br><span class="line">            n.value = feed_dict[n]</span><br><span class="line">        <span class="keyword">for</span> m <span class="keyword">in</span> n.outputs:</span><br><span class="line">            computing_graph[n].append(m)</span><br><span class="line">            nodes.append(m)</span><br><span class="line">            </span><br><span class="line">    <span class="keyword">return</span> computing_graph</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">node_x = Placeholder(name = <span class="string">&quot;x&quot;</span>)</span><br><span class="line">node_y = Placeholder(name = <span class="string">&quot;y&quot;</span>)</span><br><span class="line">node_k = Placeholder(name = <span class="string">&quot;k&quot;</span>)</span><br><span class="line">node_b = Placeholder(name = <span class="string">&quot;b&quot;</span>)</span><br><span class="line">node_linear = Node(inputs = [node_x, node_k, node_b], name = <span class="string">&quot;linear&quot;</span>)</span><br><span class="line">node_sigmoid = Node(inputs = [node_linear], name = <span class="string">&quot;sigmoid&quot;</span>)</span><br><span class="line">node_loss = Node(inputs = [node_y, node_sigmoid], name = <span class="string">&quot;loss&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">feed_dic = &#123;</span><br><span class="line">    node_x : <span class="number">3</span>,</span><br><span class="line">    node_y : random.random(),</span><br><span class="line">    node_k : random.random(),</span><br><span class="line">    node_b : <span class="number">0.50</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sorted_nodes = toplogic(convert_feed_dict_to_graph(feed_dic))</span><br><span class="line"><span class="keyword">for</span> node <span class="keyword">in</span> sorted_nodes:</span><br><span class="line">    node.forward()</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">我是b,人类赋值。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是x,人类赋值。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是y,人类赋值。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是k,人类赋值。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是linear,我没有被人类赋值，要自己计算我自己。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是sigmoid,我没有被人类赋值，要自己计算我自己。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是loss,我没有被人类赋值，要自己计算我自己。</span><br></pre></td></tr></table></figure>
<p>再增加sigmoid等类，都是从Node继承的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 线性函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Linear</span>(<span class="params">Node</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, x = <span class="literal">None</span>, weight = <span class="literal">None</span>, bias = <span class="literal">None</span>, name = <span class="literal">None</span></span>):</span></span><br><span class="line">        Node.__init__(self, inputs = [x, weight, bias], name = name)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.value = <span class="literal">None</span></span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self</span>):</span></span><br><span class="line">        k, x, b = self.inputs[<span class="number">1</span>], self.inputs[<span class="number">0</span>], self.inputs[<span class="number">2</span>]</span><br><span class="line">        self.value = k.value * x.value + b.value</span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;,自己计算，值为&#123;&#125;。\n&quot;</span>.<span class="built_in">format</span>(self.name, self.value))</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br><span class="line">        </span><br><span class="line"><span class="comment"># sigmoid函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sigmoid</span>(<span class="params">Node</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, x = <span class="literal">None</span>, name = <span class="literal">None</span></span>):</span></span><br><span class="line">        Node.__init__(self, inputs = [x], name = name)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.value = <span class="literal">None</span></span><br><span class="line">        </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_sigmoid</span>(<span class="params">self, x</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">1.</span> / (<span class="number">1</span> + np.exp(-<span class="number">1</span> * x))</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self</span>):</span></span><br><span class="line">        x = self.inputs[<span class="number">0</span>]</span><br><span class="line">        self.value = self._sigmoid(x.value)</span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;,自己计算，值为&#123;&#125;。\n&quot;</span>.<span class="built_in">format</span>(self.name, self.value))</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name     </span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="comment"># Loss函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Loss</span>(<span class="params">Node</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, y, yhat, name = <span class="literal">None</span></span>):</span></span><br><span class="line">        Node.__init__(self, inputs = [y, yhat], name = name)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.value = <span class="literal">None</span></span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self</span>):</span></span><br><span class="line">        y = self.inputs[<span class="number">0</span>]</span><br><span class="line">        yhat = self.inputs[<span class="number">1</span>]</span><br><span class="line">        self.value = np.mean(y.value - yhat.value)**<span class="number">2</span></span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;,自己计算，值为&#123;&#125;。\n&quot;</span>.<span class="built_in">format</span>(self.name, self.value))</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br></pre></td></tr></table></figure>
<p>节点的定义也改一下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">node_x = Placeholder(name = <span class="string">&quot;x&quot;</span>)</span><br><span class="line">node_y = Placeholder(name = <span class="string">&quot;y&quot;</span>)</span><br><span class="line">node_k = Placeholder(name = <span class="string">&quot;k&quot;</span>)</span><br><span class="line">node_b = Placeholder(name = <span class="string">&quot;b&quot;</span>)</span><br><span class="line">node_linear = Linear(x = node_x, weight = node_k, bias = node_b, name = <span class="string">&quot;linear&quot;</span>)</span><br><span class="line">node_sigmoid = Sigmoid(x = node_linear, name = <span class="string">&quot;sigmoid&quot;</span>)</span><br><span class="line">node_loss = Loss(y = node_y, yhat = node_sigmoid, name = <span class="string">&quot;loss&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>运行结果:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">我是y,人类赋值，值为<span class="number">0.712600098521853</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是x,人类赋值，值为<span class="number">3</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是k,人类赋值，值为<span class="number">0.08780973558938976</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是b,人类赋值，值为<span class="number">0.5</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是linear,自己计算，值为<span class="number">0.7634292067681693</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是sigmoid,自己计算，值为<span class="number">0.6820977882373328</span>。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">我是loss,自己计算，值为<span class="number">0.0009303909326931479</span>。</span><br></pre></td></tr></table></figure>
<p>现在知道了loss的值，接下来就是如何减小loss值的问题了。也就是后向传播的问题了。<br>下面实现反向求导。在节点类里增加backward()成员函数。<br>如Sigmoid类中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># sigmoid函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sigmoid</span>(<span class="params">Node</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, x = <span class="literal">None</span>, name = <span class="literal">None</span></span>):</span></span><br><span class="line">        Node.__init__(self, inputs = [x], name = name)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.value = <span class="literal">None</span></span><br><span class="line">        </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_sigmoid</span>(<span class="params">self, x</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">1.</span> / (<span class="number">1</span> + np.exp(-<span class="number">1</span> * x))</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self</span>):</span></span><br><span class="line">        x = self.inputs[<span class="number">0</span>]</span><br><span class="line">        self.value = self._sigmoid(x.value)</span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;,自己计算，值为&#123;&#125;。\n&quot;</span>.<span class="built_in">format</span>(self.name, self.value))</span><br><span class="line">        </span><br><span class="line">    <span class="comment"># 反向传播</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">backward</span>(<span class="params">self</span>):</span></span><br><span class="line">        x = self.inputs[<span class="number">0</span>]</span><br><span class="line">        self.gradients[x] = self.outputs[<span class="number">0</span>].gradients[self]*self._sigmoid(x.value) * (<span class="number">1</span> - self._sigmoid(x.value))</span><br><span class="line">        print(<span class="string">&quot;self.gradients[self.inputs[0]|&#123;&#125;&quot;</span>.<span class="built_in">format</span>(self.gradients[self.inputs[<span class="number">0</span>]]))</span><br><span class="line">            </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br></pre></td></tr></table></figure>
<p>其它类与此类似。下面就可以进行更新步骤了。<br>用函数封装一下一次训练过程:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">compute_graph</span>):</span></span><br><span class="line">    <span class="keyword">for</span> node <span class="keyword">in</span> compute_graph:</span><br><span class="line">        node.forward()</span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">backward</span>(<span class="params">compute_graph</span>):</span></span><br><span class="line">    <span class="keyword">for</span> node <span class="keyword">in</span> compute_graph[::-<span class="number">1</span>]: <span class="comment"># 实现反向</span></span><br><span class="line">        print(<span class="string">&quot;我是&#123;&#125;&quot;</span>.<span class="built_in">format</span>(node.name))</span><br><span class="line">        node.backward()</span><br><span class="line">        </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">one_epoch</span>(<span class="params">compute_graph</span>):</span></span><br><span class="line">    forward(compute_graph)</span><br><span class="line">    backward(compute_graph)</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 更新步骤</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span>(<span class="params">compute_graph</span>):</span></span><br><span class="line">    learning_rate = <span class="number">1e-1</span></span><br><span class="line">    <span class="keyword">for</span> node <span class="keyword">in</span> compute_graph:</span><br><span class="line">        <span class="keyword">if</span> node.istrainable:</span><br><span class="line">            node.value = node.value-<span class="number">1</span>*node.gradients[node]*learning_rate</span><br><span class="line">            print(node.name, node.value)</span><br></pre></td></tr></table></figure>
<p>这就完成了这个过程，输入是标量，向量版本的把运算换成矩阵运算就行了。课程还介绍了怎么把库打包发布到网上给别人用。这个我就跳过了。<br>下面练习我就自己实现一个看看。<br>具体代码看这儿<a target="_blank" rel="noopener" href="https://github.com/zwdnet/JSMPwork/blob/main/MyFrame.py">https://github.com/zwdnet/JSMPwork/blob/main/MyFrame.py</a><br>用波士顿房价预测作为测试问题，分别用我的框架和pytorch框架来解，并记录训练时间。用的数据，超参数都是一样的。<br>我的框架:<br><strong>main</strong>.testMyFrame的运行时间为 : 219.15557213081047秒       框架评分:1512498.8851033389<br>pytorch:<br><strong>main</strong>.testPytorch的运行时间为 : 358.63247944414616秒       pytorch评分:1451729.25<br>比pytorch时间短，评分也高一些(越低越好)……当然使用上还是pytorch更容易一些，因为我没有实现类似nn.Module的类，预测要自己写，而且跟神经网络的结构有关，改结构要改很多代码。<br>再来看看预测结果。<br>我的框架的:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/11.png"></p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/12.png"></p>
<p>第二张图是预测值与真实值之差的连线。<br>pytorch的。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/13.png"></p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/70/14.png"></p>
<p>最后，再到github上看看pytorch的源代码。nn模块的大多数类都直接/间接继承于Module类，类似我们框架的Node类。深度学习框架最核心的自动求导功能，是用C++写的，貌似在<a target="_blank" rel="noopener" href="https://github.com/pytorch/pytorch/blob/2b221a95997b00dcc166918f752b2ad8e921eb15/torch/csrc/autograd/autograd.cpp">这里</a>，而且貌似是用python能调用的形式写的。我多年不用c++了，看着一片头大。先略过吧。<br>学这个课程，最主要的收获是初步知道了框架实现深度学习的流程，在这个过程中，框架为我们做了哪些事。其中最关键的是反向传播使用的梯度下降法，数学原理是求导的链式法则。程序实现的原理:将计算过程抽象为图，然后采用拓扑排序的算法得到求导顺序，然后逆序依次求导。课程是直播课，老师现场敲代码，讲得很好。并没有因为是引流课程就糊弄或藏着掖着。但我并没有打算去报进阶课程，因为毕竟只是业余爱好，钱还是留着去学我的口腔专业的培训课程吧。谢谢开课吧和高民权老师的分享!<br>下次，再回到正题，尝试用深度学习解决我们原来的问题吧。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/kaggle%E7%AB%9E%E8%B5%9B/" rel="tag"># kaggle竞赛</a>
          
            <a href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/" rel="tag"># 深度学习</a>
          
            <a href="/tags/pytorch/" rel="tag"># pytorch</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/01/20/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B098%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%957-%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E5%8F%8Apytorch/" rel="next" title="量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch">
                <i class="fa fa-chevron-left"></i> 量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/01/26/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0100%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%958-LSTM/" rel="prev" title="量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM">
                量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
